use compiler::lexer;
use std::{env, fs};
use compiler::parser::{Parser, parser::SyntaxResult};
use compiler::formatter::format_ast;


fn main() {

    //读取文件
     let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        println!("Usage: {} <filename>", args[0]);
        println!("  <filename>: Path to the source file to be processed");
        std::process::exit(1);
    }

    // 确定文件名（第一个非选项参数）
    let filename = if args.len() > 1 && !args[1].starts_with('-') {
        &args[1]
    } else if args.len() > 2 && !args[2].starts_with('-') {
        &args[2]
    } else {
        println!("Error: No filename provided");
        std::process::exit(1);
    };

    let src = fs::read_to_string(filename).expect("Failed to read file");

    //println!("Source: \n{}", src);

    let list=lexer::run(&src);
    let parser = Parser::new(list.clone());
    
    //println!("语法分析结果：");
    match parser.parse() {
        SyntaxResult::Ok { ast } => {
            //println!("pass PARSER!!");
            
            // 调试：打印AST结构
            //println!("\nAST结构：");
            //println!("{:#?}", ast);
            
            // 格式化AST并输出结果
            //println!("\n格式化后的代码：");
            match format_ast(&ast) {
                Ok(formatted_code) => {
                    println!("{}", formatted_code);
                }
                Err(e) => {
                    println!("格式化错误: {}", e);
                }
            }
        }
        SyntaxResult::Err { error_indices } => {
            // 输出所有语法错误到stdout
            for error_index in error_indices {
                if error_index < list.len() {
                    let token = &list[error_index];
                    println!("Error type B at Line {}: syntax error", token.line);
                }
            }
        }
    }

    
}